package com.hxh.generater.springBoot.util;

import cn.hutool.core.collection.CollectionUtil;
import com.hxh.entity.Project;
import com.hxh.entity.ProjectDatasource;
import com.hxh.entity.po.ClassInfo;
import com.hxh.generater.springBoot.GenerationTableInfo;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * @ProjectName: AICode
 * @Package: com.hxh.generater.util
 * @ClassName: GetAllTables
 * @Author: HXH
 * @Description:
 * @Date: 2023/11/30 9:28
 */
public class GetAllTables {

    public static List<String> getTableInfo(ProjectDatasource projectDatasource) throws SQLException {
        ConnetMysql connetMysql = new ConnetMysql();
        Connection connection = connetMysql.getConnection(projectDatasource);

        Statement statement = connection.createStatement();
//        5.执行SQL的对象去执行SQL，返回结果集
        String sql = "SHOW TABLES;";
        ResultSet resultSet = statement.executeQuery(sql);
        List<String> tableNames = new ArrayList<>();
        while (resultSet.next()) {
            tableNames.add(resultSet.getString(1));
        }

//        6.释放连接
        resultSet.close();
        statement.close();
        connection.close();
        return tableNames;
    }

    public static List<ClassInfo> generationAllTableInfo(Project project) throws SQLException {
        return generationAllTableInfo(project, null);
    }

    public static List<ClassInfo> generationAllTableInfo(Project project, List<String> ignoreTableList) throws SQLException {
        ProjectDatasource projectDatasource = project.getProjectDatasource();
        List<String> tableNames = getTableInfo(projectDatasource);
        List<ClassInfo> list = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(ignoreTableList)) {
            // 创建 Pattern 对象列表
            List<Pattern> ignorePatterns = new ArrayList<>();
            for (String regex : ignoreTableList) {
                ignorePatterns.add(Pattern.compile(regex));
            }

            // 过滤不符合正则表达式的表名
            tableNames = tableNames.stream()
                    .filter(t -> ignorePatterns.stream().noneMatch(pattern -> pattern.matcher(t).matches()))
                    .collect(Collectors.toList());
        }
        for (String tableName : tableNames) {
            list.add(GenerationTableInfo.getTableInfo(project, null, tableName));
        }
        return list;
    }

    public static List<ClassInfo> generationAllTableInfoByList(Project project, List<String> tableList) throws SQLException {
        List<ClassInfo> list = new ArrayList<>();
        if (CollectionUtil.isEmpty(tableList)) {
          return list;
        }

        for (String tableName : tableList) {
            list.add(GenerationTableInfo.getTableInfo(project, null, tableName));
        }
        return list;
    }

}
